package cn.calm.swing.osgi.api;

import java.lang.reflect.Constructor;
import java.util.Hashtable;
import java.util.List;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;

import cn.calm.swing.osgi.api.entity.Project;

public abstract class SwingOsgiBundleActivator implements BundleActivator {

	protected void loadProject(BundleContext context, String projectType,Class<? extends ProjectService> clazz) {
		try {
			ServiceReference<ProjectPersistenceService> serviceReference = context
					.getServiceReference(ProjectPersistenceService.class);
			ProjectPersistenceService service = context
					.getService(serviceReference);
			List<Project> listAllByProjectType = service
					.listAllByProjectType(projectType);
			Hashtable<String, Object> dir = new Hashtable<String, Object>();
			dir.put(ProjectService.PROJECT_TYPE, projectType);
			ProjectService service1;
			ServiceRegistration<ProjectService> registerService2;
			Constructor<? extends ProjectService> constructor = clazz.getConstructor(BundleContext.class);
			
			for (Project project : listAllByProjectType) {
				dir.put(ProjectService.PROJECT_ID, project.getId());
				if(constructor==null){
					service1=clazz.newInstance();
				}else{
					service1=constructor.newInstance(context);
				}
				service1.setProject(project);
				registerService2 = context.registerService(
						ProjectService.class, service1, dir);
				ProjectService.projectServiceRegistration.put(project.getId(),
						registerService2);
			}
			context.ungetService(serviceReference);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
